package com.example.chevbook_android;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.jibble.simpleftp.SimpleFTP;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Files.FileColumns;
import android.provider.MediaStore.Images.Media;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.support.v4.app.NotificationCompat;
import android.util.AndroidRuntimeException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AfficheLogement extends Activity{
	private Logement monLogement;
	private int param1,param2;
	private String[] imageUrls;
	private ImageView imPhoto;	
	private String selectedImagePath;
	private Uri lienImage;
	private Preview mPreview;
	private static final int PHOTO_REQUEST = 0; 
	private static final int FIND_REQUEST = 1;
	private File file;
	private Modele vmodele;
	private String nomPhoto;
	private FTPClient ftp;
	private AsyncTask<String, String, Boolean> mthreadcon;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_affiche_logement);
		Bundle b = getIntent().getExtras();
		param1 = b.getInt("param1");
		monLogement = (new Modele()).trouveLogement(param1);	// Trouve logement permet de récupérer les informations du logement grâce à son identifiant 
		vmodele = new Modele();
		
		Bundle c = getIntent().getExtras();
		param2 = c.getInt("param2");	// Récupère 0 ou 1 pour afficher les différents menu 
	
		Bundle bundle = getIntent().getExtras();
		imageUrls = bundle.getStringArray("Image");
				
		// remplissage textbox 
				TextView tvAdresse =(TextView)findViewById(R.id.tvAdresse);
				TextView tvTypeHab =(TextView)findViewById(R.id.tvTypeHab);
				TextView tvSuperficie =(TextView)findViewById(R.id.tvSurf);
				TextView tvDistance =(TextView)findViewById(R.id.tvDist);
				TextView tvNbPiece=(TextView)findViewById(R.id.tvNbPlace);
				TextView tvTypeApp=(TextView)findViewById(R.id.tvTypeApp);
				TextView tvMeuble=(TextView)findViewById(R.id.tvMeuble);
				TextView tvLoyer=(TextView)findViewById(R.id.tvLoyer);
				TextView tvDescription=(TextView)findViewById(R.id.tvDescription);
				TextView tvPiece = (TextView)findViewById(R.id.tvPiece);
				Gallery gallery = (Gallery)findViewById(R.id.gallery1);
				imPhoto = (ImageView)findViewById(R.id.imageView1);
				
				// setteur textbox
				tvAdresse.setText(monLogement.getAdresse() + " " +monLogement.getCp()+ " " + monLogement.getVille());
				tvSuperficie.setText(Integer.toString(monLogement.getSurface()));
				tvNbPiece.setText(Integer.toString(monLogement.getNbpiece()));
				tvTypeApp.setText(" "+monLogement.getTypeApp());
				tvMeuble.setText(" "+monLogement.getMeuble());
				tvLoyer.setText(Double.toString(monLogement.getPrix()));
				tvDescription.setText(monLogement.getDescription());
				
				  // Méthode d'initialisation de la caméra
				
				if(monLogement.getNbpiece()==1)
				{
					tvPiece.setText(" pièce ");
				}else
				{
					tvPiece.setText(" pièces ");
				}
				
				if(monLogement.getDistance()<1000)
				{
					tvDistance.setText("0."+monLogement.getDistance()/100+" km");
				}else
				{
					tvDistance.setText(Double.toString(monLogement.getDistance()/1000)+" km");
				}	
				
				if(param2 == 0)
				{
				imPhoto.setVisibility(View.INVISIBLE);	// N'affiche pas l'image view pour récupérer la photo prise par l'appareil photo ou photo provenant du smartphone 
				gallery.setVisibility(View.VISIBLE);	// Affichage de la gallery photo si le logement possède des images 
				 gallery.setAdapter(new ImageAdapter(this,param1));
				 gallery.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							//startImagePagerActivity(position);
						}
					});
				}
				if(param2 ==1)	// L'inverse quand param2 ==0 Affichage de l'image view et non de la gallery 
				{
					gallery.setVisibility(View.INVISIBLE);
					imPhoto.setVisibility(View.INVISIBLE);
					// L'endroit où sera enregistrée la photo
					// Remarquez que mFichier est un attribut de ma classe
					
				}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.affiche_logement, menu);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		if(param2 ==0)	// Permet de rendre visible les items 
		{
			menu.findItem(R.id.menu_call).setVisible(true);
			menu.findItem(R.id.menu_star).setVisible(false);
			menu.findItem(R.id.menu_mail).setVisible(true);
			menu.findItem(R.id.menu_locate).setVisible(true);
			menu.findItem(R.id.menu_take).setVisible(false);
			menu.findItem(R.id.menu_find).setVisible(false);
			menu.findItem(R.id.menu_save).setVisible(false);
		}
		if(param2 ==1)
		{
			menu.findItem(R.id.menu_call).setVisible(false);
			menu.findItem(R.id.menu_star).setVisible(false);
			menu.findItem(R.id.menu_mail).setVisible(false);
			menu.findItem(R.id.menu_locate).setVisible(false);
			menu.findItem(R.id.menu_take).setVisible(true);
			menu.findItem(R.id.menu_find).setVisible(false);
			menu.findItem(R.id.menu_save).setVisible(true);
		}
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(param2==0)
		{			
			switch (item.getItemId()) {
					case android.R.id.home:	
						finish();
						return true;
					case R.id.menu_call:
						Intent intent = new Intent(Intent.ACTION_CALL); 
					     intent.setData(Uri.parse("tel://"+monLogement.getTelephone())); // récupère le numéro de téléphone de la personne qui a publié le logement et l'appelle
					     startActivity(intent);
						return true;
					/*case R.id.menu_star:	// Menu favori ( non fonctionnel pour le moment ) 
						//Création d'une notification .
						NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
						NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
						Notification notification = builder
						        .setContentTitle(getResources().getText(R.string.app_name))
						        .setContentText(getResources().getText(R.string.menu_star))
						        .setSmallIcon(R.drawable.ic_launcher)
						        .setWhen(System.currentTimeMillis()).build();
						notification.flags |= Notification.FLAG_AUTO_CANCEL;
						mNotificationManager.notify(0, notification);
						return true;*/
					case R.id.menu_locate:	// Menu de géolocalisation 
						Intent myIntent3 = new Intent(getApplicationContext(),Geolocalisation.class);
						myIntent3.putExtra("identifiant", monLogement.getId());
						startActivity(myIntent3);
						return true;
					case R.id.menu_mail:	// Menu envoi de mail, récupère l'adresse mail du déposant et ajoutte un titre au mail 
						Intent emailIntent = new  Intent(Intent.ACTION_SEND); 
						emailIntent.setType("message/rfc822");	// Protocole du mail ( ne pas modifier ) 
					    emailIntent.putExtra(Intent.EXTRA_EMAIL, new  String[]{monLogement.getMail()}); 
					    emailIntent.putExtra(Intent.EXTRA_SUBJECT,"Votre annonce Chevbook: " + monLogement.getTitre()); // Titre du mail 
					    startActivity(emailIntent);
						return true;
					default:
						return super.onOptionsItemSelected(item);
					}
		}
		if(param2==1)
		{
				switch (item.getItemId()) {
					case android.R.id.home:
						finish();
						return true;
					case R.id.menu_take:	// Menu pour prendre une photo 
						Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
						lienImage = setImageUri();
						intent.putExtra(MediaStore.EXTRA_OUTPUT, lienImage);
					    startActivityForResult(intent, PHOTO_REQUEST);
						return true;
					/*case R.id.menu_find:	// Menu récupérer une image sur le smartphone 
						Intent intentf = new Intent();
                        intentf.setType("image/*");	// Récupère seulement des images 
                        intentf.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intentf,"Select Picture"), FIND_REQUEST);
						return true;*/
					case R.id.menu_save:	// Menu d'envoi de la photo en FTP 
						if(nomPhoto != null)
						{
						sendFileViaFTP(file.toString());
						String[] mesparams = {Integer.toString(monLogement.getId()),monLogement.getId() +"_"+vmodele.CompteurPhoto(monLogement.getId()) ,"http://ppe4.olympe.in/Android/ajoutImageBdd.php" };
						mthreadcon = new Connexion(AfficheLogement.this).execute(mesparams);
						vmodele.enregistrePhoto(monLogement.getId() +"_"+vmodele.CompteurPhoto(monLogement.getId()), monLogement.getId());
						finish();
						}
						return true;
					default:
						return super.onOptionsItemSelected(item);
				}		
		}
		return false;
	}
	
	@Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	 // TODO Auto-generated method stub
	 super.onActivityResult(requestCode, resultCode, data);
		 //Permet l'affichage des photos dans un image view pour voir le résultat avant de pouvoir l'envoyer sur le serveur via FTP 
			/* if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK && data != null) {
				 Bundle extras = data.getExtras();
				 Bitmap photo =(Bitmap) extras.get("data"); 
			     imPhoto.setImageBitmap(photo);
			     
			 }
			 if (requestCode == FIND_REQUEST && resultCode == RESULT_OK && data != null) {  
				     Bitmap photo = (Bitmap) data.getExtras().get("data"); 
				     imPhoto.setImageBitmap(photo);
				    // Bundle extras = data.getExtras();
		 }*/
	 File imgFile = new File (Environment.getExternalStorageDirectory()+"/Chevbook/", monLogement.getId() +"_"+vmodele.CompteurPhoto(monLogement.getId()) + ".jpg");
	 if(imgFile.exists()){
		 imPhoto.setVisibility(View.VISIBLE);
	     Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
	     imPhoto.setImageBitmap(myBitmap);

	 }
	 }
	
	public Uri setImageUri() {	// Fonction qui va stocker l'image prise par l'appareil photo dans la mémoire du smartphone et va lui donner un nom ( identifiantDuLogement_numéroDeLaPhoto.jpg )
        // Store image in dcim
		File rep = new File(Environment.getExternalStorageDirectory()+"/Chevbook");
		if(!rep.exists() && !rep.isDirectory()) 
	    {	
	        rep.mkdirs();
	    }
        file = new File(Environment.getExternalStorageDirectory()+"/Chevbook/" + monLogement.getId() +"_"+vmodele.CompteurPhoto(monLogement.getId()) + ".jpg");
        nomPhoto = monLogement.getId() +"_"+vmodele.CompteurPhoto(monLogement.getId()) + ".jpg";
        Uri imgUri = Uri.fromFile(file);
        this.selectedImagePath = file.getAbsolutePath();
        return imgUri;
    }
	
	public Bitmap decodeFile(String path) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 70;

            // Find the correct scale value. It should be the power of 2.
            int scale = 1;
            while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeFile(path, o2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }
	
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
}
	
	public void sendFileViaFTP(final String imagetransferer) {	// Fonction qui va envoyer l'image sur le serveur via FTP 
        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
        try {
        SimpleFTP ftp = new SimpleFTP();


        // Connect to an FTP server on port 21.
        ftp.connect("ftp.olympe.in", 21, "ppe4", "09101994");

        // Set binary mode.
        ftp.bin();

        // Change to a new working directory on the FTP server.

        ftp.cwd("images");

        // Upload some files.
        ftp.stor(new File(imagetransferer));              

        // Quit from the FTP server.
        ftp.disconnect();
        
        }
        catch (IOException e) {
            // Jibble.
        }
            }
        });

        thread.start(); 
	 }
}
